package com.aizuda.boot.modules.business.counterparty.controller;


import cn.hutool.http.Header;
import com.aizuda.boot.modules.business.contract.dto.SingleResponse;
import com.aizuda.boot.modules.business.counterparty.entity.dto.*;
import com.aizuda.boot.modules.common.constant.enums.ResponseCodeEnum;
import com.aizuda.boot.modules.business.counterparty.entity.vo.ChangeRecordVO;
import com.aizuda.boot.modules.business.counterparty.entity.vo.LegalEntityPageRespDTO;
import com.aizuda.boot.modules.business.counterparty.entity.vo.LegalVO;
import com.aizuda.boot.modules.business.counterparty.service.LegalEntityService;
import com.aizuda.boot.modules.file.domain.entity.FileInfo;
import com.aizuda.boot.modules.file.domain.vo.FileDownloadVO;
import com.aizuda.boot.modules.file.service.FileInfoService;
import com.aizuda.boot.modules.file.util.FileResponseUtil;
import com.aizuda.core.api.ApiAssert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * 法人实体管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/legal")
@Tag(description = "/legal", name = "法人实体管理接口")
public class LegalEntityController {

    @Resource
    private LegalEntityService legalEntityService;

    @Resource
    private FileInfoService fileService;

    @PostMapping("/page")
    @Operation(summary = "分页查询法人实体列表")
    public SingleResponse<LegalEntityPageRespDTO> queryLegalEntitiesPage(@RequestBody @Validated LegalEntityQueryReqDTO reqDTO) {
        try {
            log.info("分页查询法人实体列表，请求参数：{}", reqDTO);
            LegalEntityPageRespDTO pageResult = legalEntityService.queryLegalEntitiesPage(reqDTO);
            return SingleResponse.of(pageResult);
        } catch (Exception e) {
            log.error("分页查询法人实体列表失败", e);
            return SingleResponse.failure(ResponseCodeEnum.SHOW_MSG.getCode(), "查询法人实体列表失败: " + e.getMessage());
        }
    }

    @PostMapping("/save")
    @Operation(summary = "新增法人实体")
    public Boolean save(@RequestBody @Validated CreateLegalInfoDTO dto, HttpServletRequest request) {
        try {
            log.info("新增法人实体，请求参数：{}", dto);
            return legalEntityService.saveLegal(dto, request);
        } catch (Exception e) {
            log.error("新增法人实体失败", e);
            ApiAssert.fail("新增法人实体失败" + e.getMessage());
            return false;
        }
    }


    @PostMapping("/update")
    @Operation(summary = "更新法人实体")
    public Boolean update(@RequestBody @Validated UpdateLegalInfoDTO dto, HttpServletRequest request) {
        try {
            log.info("更新法人实体，请求参数：{}", dto);
            return legalEntityService.updateLegal(dto, request);
        } catch (Exception e) {
            log.error("更新法人实体失败", e);
            ApiAssert.fail("更新法人实体失败" + e.getMessage());
            return false;
        }
    }

    @PostMapping("/updateStatus")
    @Operation(summary = "更新法人实体状态")
    public Boolean updateStatus(@RequestBody @Validated UpdateStatusDTO dto) {
        try {
            log.info("更新法人实体状态，请求参数：{}", dto);
            return legalEntityService.toggleLegalEntityStatus(dto.getId(), dto.getEnabled());
        } catch (Exception e) {
            log.error("更新法人实体状态失败", e);
            ApiAssert.fail("更新法人实体状态失败" + e.getMessage());
            return false;
        }
    }

    @GetMapping("changeRecords/{legalId}")
    @Operation(summary = "查询法人实体修改记录")
    public List<ChangeRecordVO> queryChangeRecords(@PathVariable Integer legalId) {
        log.info("查询法人实体修改记录，请求参数：{}", legalId);
        return legalEntityService.queryChangeRecords(legalId);
    }

    @Operation(summary = "上传文件更新法人实体")
    @PostMapping("/upload")
    public SingleResponse<Boolean> uploadLegal(MultipartFile file) {
        try {
            return legalEntityService.uploadCounterparty(file);
        } catch (Exception e) {
            log.error("上传文件更新交易方失败", e);
            return SingleResponse.failure(ResponseCodeEnum.ERROR.getCode(), ResponseCodeEnum.ERROR.getMsg());
        }
    }


    @Operation(summary = "下载法人实体模板")
    @GetMapping("/downloadTemplate")
    public void downLoadTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String fileName = "法人实体数据批量维护模板.xlsx";
        String resourcePath = "static/documents/" + fileName;

        ClassPathResource resource = new ClassPathResource(resourcePath);
        if (!resource.exists()) {
            FileResponseUtil.write(response, SingleResponse.failure(ResponseCodeEnum.SHOW_MSG.getCode(), "模板文件不存在: " + fileName));
            return;
        }

        long contentLength = resource.contentLength();
        FileResponseUtil.setDownloadFileHeader(response, fileName, contentLength);

        try (java.io.InputStream inputStream = resource.getInputStream()) {
            inputStream.transferTo(response.getOutputStream());
        }
    }


    @Operation(summary = "查询全部法人信息")
    @GetMapping("/list")
    public List<LegalVO> queryLegalEntities() {
        return legalEntityService.getLegalEntityList();
    }


    @Operation(summary = "删除法人实体")
    @DeleteMapping("delete/{legalId}")
    public SingleResponse<Boolean> deleteLegal(@PathVariable Integer legalId) {
        return SingleResponse.of(legalEntityService.deleteLegal(legalId));
    }


    @Operation(summary = "导出法人实习信息")
    @PostMapping("/export")
    public void exportLegalEntity(@RequestBody ExportDTO dto, HttpServletResponse response) {
        try {
            legalEntityService.exportLegalEntity(dto, response);
        }catch (Exception e) {
            log.error("导出法人实习信息失败", e);
            FileResponseUtil.write(response, SingleResponse.failure(ResponseCodeEnum.ERROR.getCode(), ResponseCodeEnum.ERROR.getMsg()));
        }

    }

} 